package itesm.coler.service;

import itesm.coler.data.TeamDAO;
import itesm.coler.data.DAOFactory;
import itesm.coler.models.Team;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Produces({"application/xml","application/json"})
@Path("/teams")
public class TeamResource {

	DAOFactory MySQLFactory = DAOFactory.getDAOFactory(DAOFactory.MySQL);
	TeamDAO teamDAO = MySQLFactory.getTeamDAO();
	
	
	@GET
	public ArrayList<Team> getAllTeams(){
		try {
			ArrayList<Team> teams = teamDAO.findAll();
			return teams;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@GET
	@Produces({ "application/xml", "application/json" })
	@Path("/team/{teamId}/")
	public Team getTeam(@PathParam("teamId") int teamId) {
		Team team = teamDAO.findTeamById(teamId);
		return team;
	}
	
	@GET
	@Produces({ "application/xml", "application/json" })
	@Path("/course/{courseId}/")
	public ArrayList<Team> getTeamsByCourse(@PathParam("courseId") String courseId) {
		ArrayList<Team> teams = teamDAO.findAllByCourse(courseId);
		return teams;
	}
	
	@PUT
	  @Path("/add")
	  @Produces("text/plain")
	  @Consumes(MediaType.APPLICATION_JSON)
	  public Response addTeam(Team team) {
	   try {
	    teamDAO.insertTeam(team);
	    String result = "Team saved : " + team;
	    return Response.status(201).entity(result).build();
	   } catch (Exception sqle){
		   sqle.printStackTrace();
		   return null;
	   }
	  }
	
	@PUT
	@Path("/modify")
	@Produces("text/plain")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response modifyTeam(Team team){
		  try {
			boolean result =teamDAO.updateTeam(team);
			System.out.println("Resultado de ModifyTeam ="+result);
			return Response.status(201).entity("ok").build();	
		  } catch (Exception sqle){
			   sqle.printStackTrace();
			   return null;
		   }
	}
	
	@DELETE
	@Path("/delete/{teamId}")
	public Response deleteTeam(@PathParam("teamId") int teamId){
		teamDAO.deleteTeam(teamId);
		return Response.status(201).entity("ok").build();
	}
	
	@PUT
	@Path("/deactivate/{teamId}")
	@Produces("text/plain")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deactivateTeam(@PathParam("teamId") int teamId){
	    teamDAO.updateTeamActiveStatus(teamId, false);
		return Response.status(201).entity("ok").build();
	}
	
	@PUT
	@Path("/activate/{teamId}")
	@Produces("text/plain")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response activateTeam(@PathParam("teamId") int teamId){
		teamDAO.updateTeamActiveStatus(teamId, true);
		return Response.status(201).entity("ok").build();
	}
	
}
